/*
CryptoJS v3.0.2
code.google.com/p/crypto-js
(c) 2009-2012 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
var CryptoJS=CryptoJS||function(o,q){var l={},m=l.lib={},n=m.Base=function(){function a(){}return{extend:function(e){a.prototype=this;var c=new a;e&&c.mixIn(e);c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),j=m.WordArray=n.extend({init:function(a,e){a=
	this.words=a||[];this.sigBytes=e!=q?e:4*a.length},toString:function(a){return(a||r).stringify(this)},concat:function(a){var e=this.words,c=a.words,d=this.sigBytes,a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b<a;b++)e[d+b>>>2]|=(c[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535<c.length)for(b=0;b<a;b+=4)e[d+b>>>2]=c[b>>>2];else e.push.apply(e,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,e=this.sigBytes;a[e>>>2]&=4294967295<<32-8*(e%4);a.length=o.ceil(e/4)},clone:function(){var a=
	n.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var e=[],c=0;c<a;c+=4)e.push(4294967296*o.random()|0);return j.create(e,a)}}),k=l.enc={},r=k.Hex={stringify:function(a){for(var e=a.words,a=a.sigBytes,c=[],d=0;d<a;d++){var b=e[d>>>2]>>>24-8*(d%4)&255;c.push((b>>>4).toString(16));c.push((b&15).toString(16))}return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-4*(d%8);return j.create(c,b/2)}},p=k.Latin1={stringify:function(a){for(var b=
	a.words,a=a.sigBytes,c=[],d=0;d<a;d++)c.push(String.fromCharCode(b[d>>>2]>>>24-8*(d%4)&255));return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return j.create(c,b)}},h=k.Utf8={stringify:function(a){try{return decodeURIComponent(escape(p.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return p.parse(unescape(encodeURIComponent(a)))}},b=m.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=j.create();
	this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,c=b.words,d=b.sigBytes,f=this.blockSize,i=d/(4*f),i=a?o.ceil(i):o.max((i|0)-this._minBufferSize,0),a=i*f,d=o.min(4*a,d);if(a){for(var h=0;h<a;h+=f)this._doProcessBlock(c,h);h=c.splice(0,a);b.sigBytes-=d}return j.create(h,d)},clone:function(){var a=n.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});m.Hasher=b.extend({init:function(){this.reset()},
	reset:function(){b.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);this._doFinalize();return this._hash},clone:function(){var a=b.clone.call(this);a._hash=this._hash.clone();return a},blockSize:16,_createHelper:function(a){return function(b,c){return a.create(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return f.HMAC.create(a,c).finalize(b)}}});var f=l.algo={};return l}(Math);
	(function(o){function q(b,f,a,e,c,d,g){b=b+(f&a|~f&e)+c+g;return(b<<d|b>>>32-d)+f}function l(b,f,a,e,c,d,g){b=b+(f&e|a&~e)+c+g;return(b<<d|b>>>32-d)+f}function m(b,f,a,e,c,d,g){b=b+(f^a^e)+c+g;return(b<<d|b>>>32-d)+f}function n(b,f,a,e,c,d,g){b=b+(a^(f|~e))+c+g;return(b<<d|b>>>32-d)+f}var j=CryptoJS,k=j.lib,r=k.WordArray,k=k.Hasher,p=j.algo,h=[];(function(){for(var b=0;64>b;b++)h[b]=4294967296*o.abs(o.sin(b+1))|0})();p=p.MD5=k.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,
	2562383102,271733878])},_doProcessBlock:function(b,f){for(var a=0;16>a;a++){var e=f+a,c=b[e];b[e]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360}for(var e=this._hash.words,c=e[0],d=e[1],g=e[2],i=e[3],a=0;64>a;a+=4)16>a?(c=q(c,d,g,i,b[f+a],7,h[a]),i=q(i,c,d,g,b[f+a+1],12,h[a+1]),g=q(g,i,c,d,b[f+a+2],17,h[a+2]),d=q(d,g,i,c,b[f+a+3],22,h[a+3])):32>a?(c=l(c,d,g,i,b[f+(a+1)%16],5,h[a]),i=l(i,c,d,g,b[f+(a+6)%16],9,h[a+1]),g=l(g,i,c,d,b[f+(a+11)%16],14,h[a+2]),d=l(d,g,i,c,b[f+a%16],20,h[a+3])):48>a?(c=
	m(c,d,g,i,b[f+(3*a+5)%16],4,h[a]),i=m(i,c,d,g,b[f+(3*a+8)%16],11,h[a+1]),g=m(g,i,c,d,b[f+(3*a+11)%16],16,h[a+2]),d=m(d,g,i,c,b[f+(3*a+14)%16],23,h[a+3])):(c=n(c,d,g,i,b[f+3*a%16],6,h[a]),i=n(i,c,d,g,b[f+(3*a+7)%16],10,h[a+1]),g=n(g,i,c,d,b[f+(3*a+14)%16],15,h[a+2]),d=n(d,g,i,c,b[f+(3*a+5)%16],21,h[a+3]));e[0]=e[0]+c|0;e[1]=e[1]+d|0;e[2]=e[2]+g|0;e[3]=e[3]+i|0},_doFinalize:function(){var b=this._data,f=b.words,a=8*this._nDataBytes,e=8*b.sigBytes;f[e>>>5]|=128<<24-e%32;f[(e+64>>>9<<4)+14]=(a<<8|a>>>
	24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4*(f.length+1);this._process();b=this._hash.words;for(f=0;4>f;f++)a=b[f],b[f]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360}});j.MD5=k._createHelper(p);j.HmacMD5=k._createHmacHelper(p)})(Math);


/*
* webimjsdk
* 封装调用评论服务： 发送消息、获取历史消息、获取子消息接口
* 集成 webimsdk 登录、加入、退出主题接口
*
*/
(function(){
	var Paasim_host;
	//var butelxmlhttp = null;//定义http对象
	var butelNameSpace = "PaaSWebIM";
 	window[butelNameSpace] = {};//注册命名空间到window对象上
	
	//帐号模式，0-表示独立模式，1-表示托管模式
    var accountMode = 1;
   // var sdkAppID = 1400125591;// 现网：1400125591，测试网1400138161
	//var appIDAt3rd=1400125591;// 现网：1400125591，测试网1400138161
    var sdkAppID = 1400138161;// 现网：1400125591，测试网1400138161
   var appIDAt3rd=1400138161;// 现网：1400125591，测试网1400138161
    var accountType = 72;
	
	if (!window.paasImSdk) {
		window.paasImSdk = {};
	}
	
	//外部传入监听事件
	var _businessListeners = {
         "onConnNotify": onConnNotify, //选填
         "jsonpCallback": jsonpCallback, //IE9(含)以下浏览器用到的jsonp回调函数,移动端可不填，pc端必填
         "onBigGroupMsgNotify": onBigGroupMsgNotify, //监听新消息(大群)事件，必填
         "onMsgNotify": onMsgNotify,//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
		 "onGroupSystemNotifys": onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
	 };
	 
	 var outerListeners={};

	
	//监听（多终端同步）群系统消息方法
    //注意每个数字代表的含义，比如，
    //1表示监听申请加群消息，2表示监听申请加群被同意消息，3表示监听申请加群被拒绝消息等
      var onGroupSystemNotifys = {
        // "1": onApplyJoinGroupRequestNotify, //申请加群请求（只有管理员会收到,暂不支持）
        // "2": onApplyJoinGroupAcceptNotify, //申请加群被同意（只有申请人能够收到,暂不支持）
        // "3": onApplyJoinGroupRefuseNotify, //申请加群被拒绝（只有申请人能够收到,暂不支持）
        // "4": onKickedGroupNotify, //被管理员踢出群(只有被踢者接收到,暂不支持)
        // "5": onDestoryGroupNotify, //群被解散(全员接收)
        // "6": onCreateGroupNotify, //创建群(创建者接收,暂不支持)
        // "7": onInvitedJoinGroupNotify, //邀请加群(被邀请者接收,暂不支持)
        // "8": onQuitGroupNotify, //主动退群(主动退出者接收,暂不支持)
        // "9": onSetedGroupAdminNotify, //设置管理员(被设置者接收,暂不支持)
        // "10": onCanceledGroupAdminNotify, //取消管理员(被取消者接收,暂不支持)
        // "11": onRevokeGroupNotify, //群已被回收(全员接收)
        // "255": onCustomGroupNotify//用户自定义通知(默认全员接收)
      };
	
	// var isAccessFormalEnv = false;//是否访问正式环境
    // if (webim.Tool.getQueryString("isAccessFormalEnv") == "false") {
        // isAccessFormalEnv = false;//访问测试环境
    // }
    // var isLogOn = true;//是否在浏览器控制台打印sdk日志

    //其他对象，选填
    // var options = {
        // 'isAccessFormalEnv': isAccessFormalEnv,//是否访问正式环境，默认访问正式，选填
        // 'isLogOn': isLogOn//是否开启控制台打印日志,默认开启，选填
    // };
	
	//当前用户身份
    var loginInfo = {
        'sdkAppID': sdkAppID, //用户所属应用id,必填
        'appIDAt3rd': appIDAt3rd, //用户所属应用id，必填
        'accountType': accountType, //用户所属应用帐号类型，必填
        'userSig': "", //当前用户身份凭证，必须是字符串类型，选填
	   // 'identifier': identifier, //当前用户ID,必须是否字符串类型，选填
       // 'identifierNick': "null", //当前用户昵称，选填
       // 'headurl': ''//当前用户默认头像，选填
    };
	
	
	var urlEncode = function(param, key, encode) {
		if (param==null) return '';
		var paramStr = '';
		var t = typeof (param);
		if (t == 'string' || t == 'number' || t == 'boolean') {
			paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param); 
		} 
		else {
			for (var i in param) {
				var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
				paramStr += urlEncode(param[i], k, encode)
			}
		}
		return paramStr;
	}
	
	/**
	* 外部设置工作参数
	* @param {json对象} params
	*/
	function setOptions(options){
		window.paasImSdk.url=options.paasimHost;
		window.paasImSdk.appkey=options.appkey;
		window.paasImSdk.refreshkey=options.appsecret;
		
		Paasim_host=options.paasimHost;
	}
	
	/**
	* IE9(含)以下浏览器用到的jsonp回调函数
	*/
	function setJsonpLastRspData(rspData){
		//设置接口返回的数据
		webim.setJsonpLastRspData(rspData);
	}
	
	
	/**
	 * 登录接口【评论】
	 * @param: {用户对象信息} userinfo：｛uid,nickname,faceurl｝
	 * @param {监听事件} listeners
     * @param {其他对象} options
	 * @param {成功回调函数} cbOK
	 * @param {失败回调函数} cbErr
	 */
	function login(userinfo,listeners,options,cbOK,cbErr){
	
		outerListeners=listeners;
		if (userinfo.uid || userinfo.uid!="undefined"){
			loginInfo.identifier=userinfo.uid;
		}
		else{
			loginInfo.identifier=null;
		}
		if (userinfo.nickname || userinfo.nickname!="undefined"){
			loginInfo.identifierNick=userinfo.nickname;
		}else{
			loginInfo.identifierNick='null';
		}
		if (userinfo.faceurl || userinfo.faceurl!="undefined"){
			loginInfo.headurl=userinfo.faceurl;
		}
		loginInfo.userSig=null;
		
		webim.login(loginInfo, _businessListeners, options, 
		function(rep) {
            webim.Log.info('webim登录成功');
			var status={"ActionStatus":rep.ActionStatus};
			var info={"code":rep.ErrorCode,"msg":rep.ErrorInfo,"result":status};
			cbOK(info);
        },  function(err) {
			var status={"ActionStatus":err.ActionStatus};
			var info={"code":-1,"msg": err.ErrorInfo,"result":status};
			cbErr(info);
        });
	}


	function onBigGroupMsgNotify(msgList) {
		//业务处理，如数据格式化。。。

		if(msgList&&msgList.length>0){
			var newelems=[];
			for(var i=0;i<msgList.length;i++){
				var model=msgList[i];
				for(var j=0;j<model.elems.length;j++){
					var ele=model.elems[j];
					if(ele.type=="TIMCustomElem"){
						newelems.push(ele);
					}
				}
				msgList[i].elems=newelems;
			}
			outerListeners.onBigGroupMsgNotify(msgList);	
		}
	  }

	  function jsonpCallback(rspData) {
		//设置接口返回的数据
		PaaSWebIM.setJsonpLastRspData(rspData);
	  }

	  function onMsgNotify(newMsgList) {
	//	_businessListeners.onMsgNotify(newMsgList);
	  }

	   //监听连接状态回调变化事件
	 function onConnNotify(resp) {
		 if(outerListeners.onConnNotify && outerListeners.onConnNotify instanceof Function){
			outerListeners.onConnNotify(resp);
		 }
		
        switch (resp.ErrorCode) {
            case webim.CONNECTION_STATUS.ON:
                //webim.Log.warn('连接状态正常...');
                break;
            case webim.CONNECTION_STATUS.OFF:
                webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
                break;
            default:
                webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
                break;
        }
    };
	
	/**
	 * 加入主题【评论】
	 * @param {群组/topicid} groupId
	 * @param {成功回调函数} cbOK
	 * @param {失败回调函数} cbErr
	 */
	function applyJoinBigGroup(groupId,cbOK,cbErr) {
		var options = {
        'GroupId': groupId //群id
		};
		webim.applyJoinBigGroup(options,
        function(resp) {
            if (resp.JoinedStatus && resp.JoinedStatus == 'JoinedSuccess') {
                webim.Log.info('进群成功');
				var data={"JoinedStatus":"JoinedSuccess"};
                var info={
					"code":0,
					"msg": "加入主题成功",
					"result": data
				};
				cbOK(info);
            } else {
				var info={"code":-1001,"msg":"加入主题失败"};
               cbOK(info);
            }
        },
        function(err) {
			var info={"code":-1,"msg": err.ErrorInfo};
            cbErr(err);
        });
	}
	
	/**
	 * 退出主题【评论】
	 * @param {群组/topicid} groupId
	 * @param {成功回调函数} cbOK
	 * @param {失败回调函数} cbErr
	 */
	function quitBigGroup(groupId,cbOK,cbErr) {
		var options = {
        'GroupId': groupId//群id
		};
		webim.quitBigGroup(options,
            function (resp) {
                webim.Log.info('退群成功');
				 var info={
					"code":0,
					"msg": "加入主题成功",
					"result": resp
				};
				cbOK(info);
            },
            function (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
                cbErr(err.ErrorInfo);
            }
		);
	}
	
	/**
	 * http发送主题消息到PaasIM
	 * @param: {输入参数集，具体包含以下几个} params
		 * @param {接口参数} params
		 * @param {appid} appkey
		 * @param {消息类型} msgtype
		 * @param {成功回调函数} cbOK
		 * @param {失败回调函数} cbErr
	 */
	function butelPaasSendmessage(obj, appkey, refreshkey,cbOK,cbErr){
		
		if (!refreshkey || refreshkey=="undefined") {
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
			// return;
		}
		// 输入参数
		var model = JSON.stringify(obj);
		// .replace(/\"/g, '\\"')
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=send' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(model).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;
		
		var butelxmlhttp=null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"reqparams": obj,
						"result": data.result
					};
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("POST", Paasim_host + butelPaasSendmsgInterface + urlparam, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send(model);
	}
	
	/**
	 * 获取主题消息总数
		 * @param {接口参数} obj
		 * @param {appid} appkey
		 * @param {消息类型} msgtype
		 * @param {成功回调函数} cbOK
		 * @param {失败回调函数} cbErr
	 */
	function butelPaasGetTopicMsgCount(topicids, appkey, refreshkey,cbOK,cbErr){

		if (!refreshkey || refreshkey=="undefined") {
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
			// return;
		}
		// 输入参数
		var model = JSON.stringify(topicids);
		// .replace(/\"/g, '\\"')
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=count' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(model).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;
		var butelxmlhttp = null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"result": data.result
					};
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("POST", Paasim_host + butelPaasGetTopicMsgCountInterface + urlparam, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send(model);
	}
	
	/**
	 * http发送子消息到PaasIM
	 * @param: {输入参数集，具体包含以下几个} params
		 * @param {接口参数} params
		 * @param {appid} appkey
		 * @param {消息类型} msgtype
		 * @param {成功回调函数} cbOK
		 * @param {失败回调函数} cbErr
	 */
	function butelPaasSendSubmessage(obj, appkey, refreshkey,cbOK,cbErr){
		
		if (!refreshkey || refreshkey=="undefined") {
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
			// return;
		}
			
		// 输入参数
		var model = JSON.stringify(obj);
		// .replace(/\"/g, '\\"')
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=sendsubmsg' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(model).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;
		var butelxmlhttp = null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"reqparams": obj,
						"result": data.result
					};
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		
		butelxmlhttp.open("POST", Paasim_host + butelPaasSendSubmsgInterface + urlparam, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send(model);
	}
	
	/**
	 * http获取历史主题消息
	 * @param {接口参数} params
	 * @param {业务平台分配} appkey
	 * @param {业务平台分配} refreshkey
	 * @param {成功回调函数} cbOK
	 * @param {失败回调函数} cbErr
	 */
	function butelPaasGetHismessage(obj, appkey, refreshkey,cbOK,cbErr){
		
		if (!refreshkey || refreshkey=="undefined") {
			// alert('缺少参数：refreshkey');
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
		}
		
		var params=urlEncode(obj).slice(1);
		
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=getlist' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(params).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;

		var model = params+ '&' + urlparam;
		var butelxmlhttp = null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"pagingrows": data.pagingrows
					};

					if (!info.pagingrows || info.pagingrows.totalcount == undefined
						|| info.pagingrows.totalcount == null
					    || !info.pagingrows.rows) {
						info.code = -133;
						info.msg="获取历史消息失败！接口返回的数据结构有误";
						cbErr(info);
						// console.log('获取历史消息失败！接口返回的数据结构有误');
						return;
					}
					
					if (info.pagingrows.rows.length > 0) {
						window.paasImSdk.timestamp = info.pagingrows.rows[info.pagingrows.rows.length - 1].timestamp;
					}
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("GET", Paasim_host + butelPaasGetHismsgInterface + model, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send();
	}
	
	/**
	 * http获取子消息
	 * @param {接口参数} params
	 * @param {业务平台分配} appkey
	 * @param {业务平台分配} refreshkey
	 * @param {成功回调函数} cbOK
	 * @param {失败回调函数} cbErr
	 */
	function butelPaasGetHisSubmessage(obj, appkey, refreshkey,cbOK,cbErr){
		
		if (!refreshkey || refreshkey=="undefined") {
			// alert('缺少参数：refreshkey');
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
		}
		
		var params=urlEncode(obj).slice(1);
		
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=getsubmsgs' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(params).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;

		var model = params+ '&' + urlparam;

		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		// readyState变化时的回调
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"pagingrows": data.pagingrows
					};

					if (!info.pagingrows || info.pagingrows.totalcount == undefined
						|| info.pagingrows.totalcount == null
					    || !info.pagingrows.rows) {
						info.code = -133;
						cbErr(info);
						// console.log('获取子消息失败！接口返回的数据结构有误');
						return;
					}			
					if (info.pagingrows.rows.length > 0) {
						window.paasImSdk.subtimestamp = info.pagingrows.rows[info.pagingrows.rows.length - 1].timestamp;
					}
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("GET", Paasim_host + butelPaasGetHisSubmsgInterface + model, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send();
	}

	/**
	 * 获取消息在线人数
		 * @param {接口参数} obj 
		 * @param {appid} appkey
		 * @param {消息类型} msgtype
		 * @param {成功回调函数} cbOK
		 * @param {失败回调函数} cbErr
	 */
	function butelPaasGetTopicsuserNum(topicids, appkey, refreshkey,cbOK,cbErr){

		if (!refreshkey || refreshkey=="undefined") {
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
			// return;
		}
		// 输入参数
		var model = JSON.stringify(topicids);
		// .replace(/\"/g, '\\"')
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=gettopicsusernum' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(model).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;
		var butelxmlhttp = null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null,
						"result": data.result
					};
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("POST", Paasim_host + butelPaasGetTopicsuserNumInterface + urlparam, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send(model);
	}

	/**
	 * 消息操作（点赞、嘘）
		 * @param {接口参数} obj 
		 * @param {appid} appkey
		 * @param {消息类型} msgtype
		 * @param {成功回调函数} cbOK
		 * @param {失败回调函数} cbErr
	 */
	function butelPassOperate(operateInfo, appkey, refreshkey,cbOK,cbErr){

		if (!refreshkey || refreshkey=="undefined") {
			console.log('缺少参数,refreshkey');
			refreshkey = 'ABC';
			// return;
		}
		// 输入参数
		var model = JSON.stringify(operateInfo);
		// .replace(/\"/g, '\\"')
		var timestamp = Date.parse(new Date());
		var urlparam;
		var sign = 'service=operate' + '&securitykey=' + refreshkey +
			'&timestamp=' + timestamp + '&param=' + CryptoJS.MD5(model).toString();
		sign = CryptoJS.MD5(sign).toString();
		urlparam = 'appkey=' + appkey + '&timestamp=' + timestamp + '&sign=' + sign;
		var butelxmlhttp = null;
		if (window.XMLHttpRequest) {
			// IE7+, Firefox, Chrome, Opera, Safari 代码
			butelxmlhttp = new XMLHttpRequest();
		} else {
			// IE6, IE5 代码
			butelxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		butelxmlhttp.onreadystatechange = function() {
			try {
				if (butelxmlhttp.readyState == 4 && butelxmlhttp.status == 200) {
					var data = JSON.parse(butelxmlhttp.responseText);
					var state = data.state;
					var info = {
						"code": state ? state.rc : null,
						"msg": state ? state.msg : null
					};
					cbOK(info);
				}
			} catch (err) {
				var info={"code":-1,"msg": err.ErrorInfo};
				cbErr(info);
			}
		};
		butelxmlhttp.open("POST", Paasim_host + butelPassOperateInterface + urlparam, true);
		butelxmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
		butelxmlhttp.send(model);
	}
	
	
	// PaasIM接口
	var butelPaasSendmsgInterface = "/webapi/message/send?";
	var butelPaasSendSubmsgInterface = "/webapi/message/sendsubmsg?";
	var butelPaasGetHismsgInterface = "/webapi/message/getlist?";
	var butelPaasGetHisSubmsgInterface = "/webapi/message/getsubmsgs?";
	var butelPaasGetTopicMsgCountInterface="/webapi/message/count?";
	var butelPaasGetTopicsuserNumInterface="/webapi/topic/message/gettopicsusernum?";
	var butelPassOperateInterface = "/webapi/message/operate?";
	
	// PaasIM http接口----------start--------------------
	window[butelNameSpace]["setOptions"] = setOptions; //设置工作参数
	window[butelNameSpace]["butelPaasSendmessage"] = butelPaasSendmessage; //发送消息
	window[butelNameSpace]["butelPaasSendSubmessage"] = butelPaasSendSubmessage; //发送子消息
	window[butelNameSpace]["butelPaasGetHismessage"] = butelPaasGetHismessage; //获取历史消息
	window[butelNameSpace]["butelPaasGetHisSubmessage"] = butelPaasGetHisSubmessage; //获取子消息
	window[butelNameSpace]["butelPaasGetTopicMsgCount"] = butelPaasGetTopicMsgCount; //获取子消息
	window[butelNameSpace]["butelPaasGetTopicsuserNum"]=butelPaasGetTopicsuserNum;  //获取消息在线人数
	window[butelNameSpace]["butelPassOperate"]=butelPassOperate; // 消息操作（点赞、嘘）
	// PaasIM http接口---------- end --------------------
	
	// webimsdk----------start--------------------
	window[butelNameSpace]["login"]=login;
	window[butelNameSpace]["applyJoinBigGroup"]=applyJoinBigGroup;
	window[butelNameSpace]["quitBigGroup"]=quitBigGroup;
	window[butelNameSpace]["setJsonpLastRspData"]=setJsonpLastRspData;
	// webimsdk----------start--------------------
})();